<template>
	<view class="page page-block">
		<status-bar></status-bar>
		<cl-message ref="message"></cl-message>
		<view class="navigation">
			<image class="nav-close" src="/static/icon/add_close.png" @click="back"></image>
			<text class="nav-text">发布拍品</text>
			<!-- #ifndef MP-WEIXIN -->
			<button class="nav-btn" :disabled="isDisabled" @click="publish">发布</button>
			<!-- #endif -->

		</view>
		<view class="page-wrapper">
			<view class="input-wrapper">
				<cl-select v-model="type" :options="typeList" placeholder="请选择拍品类型" @change="dataChange"></cl-select>
				<input type="text" placeholder="标题" maxlength="15" v-model="title" @input="dataChange" />
				<textarea placeholder="详细描述一下拍品" maxlength="50" v-model="info" @input="dataChange" />
				<KXDateTime class="date" :data='end_date' :start='start' :end='end' default="start" @rundata='dataChange'></KXDateTime>
				<input type="digit" placeholder="起拍价(最低1元)" maxlength="7" v-model="startPrice" @input="dataChange"/>
				<input type="digit" placeholder="加价幅度(最低1元)" maxlength="7" v-model="markupRange" @input="dataChange"/>
			</view>
			<zw-upload-img class="image-upload" :num="imageNum" :dataList="imageList" @chooseImg="chooseImg"></zw-upload-img>
			<!-- #ifdef MP-WEIXIN -->
			<button class="nav-btn" :disabled="isDisabled" @click="publish">发布</button>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	// 引入手机状态栏留空组件
	import statusBar from "@/components/status-bar/status-bar.vue"
	// 引入日期选择器
	import KXDateTime from "@/components/kx-datetime/kx-datetime.vue"
	// 图片选择器
	import zwUploadImg from '@/components/zw-upload-img/zw-upload-img.vue'
	export default {
		components: {
			statusBar,
			KXDateTime,
			zwUploadImg
		},
		data() {
			let nowTime = new Date();
			let start = new Date(nowTime);
			start.setDate(nowTime.getDate() + 1);
			let starty = start.getFullYear(); //开始年份
			let startm = start.getMonth() + 1; //开始月份
			let startd = start.getDate(); //开始天
			let starth = start.getHours(); //开始小时
			var startStr = starty + "/" + startm + "/" + startd + " " + starth + ":00:00";
			
			let end = new Date(start);
			end.setDate(start.getDate() + 30);
			let endy = end.getFullYear(); //开始年份
			let endm = end.getMonth() + 1; //开始月份
			let endd = end.getDate(); //开始天
			let endh = end.getHours(); //开始小时
			var endStr = endy + "/" + endm + "/" + endd + " " + endh + ":00:00";
			return {
				type: '',// 拍品类型
				title: '',// 拍品标题
				info: '',// 拍品信息
				date: '',// 发布时间(自动生成)
				end_date: '',// 拍卖结束时间
				startPrice: '',// 起拍价
				markupRange: '',// 加价幅度
				images: '',//图片地址
				tag: 1,// 拍卖标识 0(已拍卖) / 1(正在拍卖) / 2(流拍)
				look: 0,// 浏览量
				uid: '',// 用户id
				typeList: [
					{
						label: "手机",
                        value: 1
					},
					{
						label: "电脑",
					    value: 2
					},
					{
						label: "数码",
					    value: 3
					},
					{
						label: "图书",
					    value: 4
					},
					{
						label: "杂物",
					    value: 5
					},
					{
						label: "其他",
					    value: 6
					}
				],
				start: startStr,
				end: endStr,
				imageNum: 3,
				imageList: [],
				isDisabled: true,
				lotId: ''
			}
		},
		methods: {
			// 监听返回事件
			back() {
				if (getCurrentPages().length <= 1) {
					uni.switchTab({
						url: '/' + this.$common.pagePath
					});
				} else {
					uni.navigateBack({
						delta: 1
					})
				}
			},
			dataChange(e) {
				if (e.target != null) {
					if (e.target.id == "date") {
						this.end_date = e.val;
					}
				}
				if (this.type != '' && this.title.trim() != '' && this.info.trim() != '' && this.end_date != '' && this.startPrice.trim() != '' && this.markupRange.trim() != '') {
					this.isDisabled = false;
				} else {
					this.isDisabled = true;
				}
			},
			chooseImg() { //选择图片
				uni.chooseImage({
					sourceType: ['camera', 'album'],
					sizeType: ['compressed', 'original'],
					count: this.imageNum - this.imageList.length,
					success: res => {
						this.imageList = this.imageList.concat(res.tempFilePaths);
					}
				});
			},
			publish() {
				if (this.title.trim().length < 5) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "标题字数不足",
						duration: 2000,
						iconSize: 24
					});
					return
				}
				if (this.info.trim().length < 5) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "详情字数不足",
						duration: 2000,
						iconSize: 24
					});
					return
				}
				if (this.end_date == null || this.end_date.length <= 0) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "未选择结束时间",
						duration: 2000,
						iconSize: 24
					});
					return
				}
				// 获得当前时间
				let nowTime = new Date();
				// 获得结束拍卖时间
				let time = new Date(this.end_date.replace(/-/g,"/"));
				// 得到相差的小时数
				let hour = (time.getTime() - nowTime.getTime()) / (3600 * 1000);
				if (hour < 12) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "当前页面已过期 请返回后重进",
						duration: 2000,
						iconSize: 24
					});
					return
				}
				if (this.startPrice == null || this.startPrice.length <= 0 || parseFloat(this.startPrice) < 1) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "起拍价不足1元",
						duration: 2000,
						iconSize: 24
					});
					return
				}
				if (this.markupRange == null || this.markupRange.length <= 0 || parseFloat(this.markupRange) < 1) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "加价幅度不足1元",
						duration: 2000,
						iconSize: 24
					});
					return
				}
				if (this.imageList.length <= 0) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "请选择最少一张拍品图片",
						duration: 2500,
						iconSize: 24
					});
					return
				}
				if (!this.$common.hasLogin) {
					uni.navigateTo({
						url:'../login/login?url=add'
					})
				}
				let addInfo = {
					type: this.type,// 拍品类型
					title: this.title,// 拍品标题
					info: this.info,// 拍品信息
					date: this.getNowFormatDate(),// 发布时间(自动生成)
					endDate: this.end_date,// 拍卖结束时间
					startPrice: this.startPrice,// 起拍价
					markupRange: this.markupRange,// 加价幅度
					tag: 1,// 拍卖标识 0(已拍卖) / 1(正在拍卖) / 2(流拍)
					look: 0,// 浏览量
					uid: this.$common.user.uid
				};
				this.$common.request(this.$serverUrl + "lot", addInfo, "POST", this.successCallback);
			},
			getNowFormatDate() {
				var date = new Date();
				var seperator1 = "-";
				var seperator2 = ":";
				var year = date.getFullYear();
				var month = date.getMonth() + 1;
				var strDate = date.getDate();
				var hour = date.getHours();
				var min = date.getMinutes();
				var sec = date.getSeconds();
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (strDate >= 0 && strDate <= 9) {
					strDate = "0" + strDate;
				}
				var currentdate = year + seperator1 + month + seperator1 + strDate + " " + hour + seperator2 + min + seperator2 + sec;
				return currentdate;
			},
			successCallback(res) {
				if (res.data.statusCode == "200") {
					if (res.data.msg == "ok") {
						let flag = 0;
						if (this.imageList.length <= 0) {
							this.lotId = res.data.data[0].lotId;
							this.$common.showModal("发布成功", false, this.addSuccess);
							return;
						}
						for (let i = 0; i < this.imageList.length; i++) {
							uni.uploadFile({// 上传图片
								url: this.$serverUrl + "lot/image",
								filePath: this.imageList[i],
								formData: {
									'imageNum': i
								},
								name: 'file',
								success: (uploadFileRes) => {
									if (uploadFileRes.statusCode == "200") {
										flag = flag + 1;
										if (flag < this.imageList.length) {
											this.images = this.images + uploadFileRes.data + "?";
										} else {
											this.images = this.images + uploadFileRes.data;
											this.updateImages()
										}
									}
								}
							});
						}
					}
				}
			},
			updateImages() {// 上传images地址
				let arr = this.images.split('?');
				let arrImageName = [];
				for (let i = 0; i < arr.length; i++) {
					let arrIndex = arr[i].lastIndexOf('.');
					let nameIndex = arr[i].substring(arrIndex - 1, arrIndex);
					arrImageName[nameIndex] = arr[i];
				}
				this.images = [];
				let images = {
					'images': arrImageName.join('?')
				};
				this.$common.request(this.$serverUrl+"lot/images", images, "GET", this.updateInfoSuccess);
				
			},
			updateInfoSuccess(res) {
				if (res.data.statusCode == 200) {
					if (res.data.msg == "ok") {
						this.lotId = res.data.data[0].lotId;
						this.$common.showModal("发布成功", false, this.addSuccess);
					}
				}
			},
			addSuccess(res) {
				if (res.confirm || res.cancel) {
					uni.redirectTo({
						url: '../lotDetail/lotDetail?lotId=' + this.lotId
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	@import url("add.css");
	/deep/ .cl-select {
		padding: 10rpx 30rpx;
		background-color: #F5F5F5;
		border: solid 2px #F5F5F5;
		border-radius: 15px;
		font-size: 16px;
		transition: 0.3s ease;
		&__icon {
			display: none;
		}
		&__placeholder {
			color: #808080;
		}
	}
	/deep/ .cl-select:hover {
		border: solid 5upx #2196F3;
	}
	/deep/ .cl-message {
		&__content {
			font-size: 16px;
		}
	}
</style>
